<?php
//用于生成行模式的表单
class FormlineModel extends Model {
	protected $tableName = 'form';
	
	//获字段列表
	public function getFieldList(){
		$fielddb = M('Field');
		$form = $this ->find();
		if(!$form){
			$this->error = '表单不存在！';
			return false;
		}
		//找到这个FORM里面的字段
		$field = $fielddb -> where(array('form_id' => $form['id'])) -> order('sort') -> select();
		if(!$field){
			$this->error = '表单中没有字段信息！';
			return false;
		}
		//都正常了
		return $field;
	}
	
	//生成字段数组
	public function getFieldArray($task_id = 0){
		$list = $this->getFieldList();
		foreach($list as $k => $v){
			$list[$k]['html'] = $this->fieldDisposebootstrap($v);
			$list[$k]['inputhidden'] = $this->getHiddenAll($v['form_id'], $task_id);
		}
		return $list;
	}
	
	//获取表单所用全部隐藏域
	private function getHiddenAll($form_id, $task_id = 0){
		$data = $this->where(array('id' => $form_id)) -> find();
		$ret = '
<input type="hidden" name="formula[]" value="'.$data['formula'].'">
<input type="hidden" value="'.$data['approver'].'" name="approver[]">
<input type="hidden" value="'.$data['approvername'].'" name="approvername[]">
<input type="hidden" name="form_id[]" value="'.$data["id"].'">
<input type="hidden" id="_sendtype" name="status[]" value="-1">';
if($task_id > 0){
	$ret .= '<input type="hidden" name="task_id[]" value="'.$task_id.'">';
}
        return $ret;
	}
	
	//生成纯字符文本
	public function getFormText($formid, $data){
		$fielddb = M('Field');
		//这里生成的文本要在saveform中调用，用于实现APP推送文本信息
		$field = $fielddb -> where(array('form_id' => $formid)) -> order('sort') -> select();
		$ret = array();
		foreach($field as $k => $v){
			if($v['f_type'] == 8){
				$data[$v['f_name']] = date('Y-m-d H:i', $data[$v['f_name']]);
			}
			$ret[] = $this->getFieldText($v['id'], $data[$v['f_name']]);
		}
		return implode("\n", $ret);
	}
	//生成纯字符文本,针对单个字段
	public function getFieldText($fieldid, $data){
		//这里生成的文本要在saveform中调用，用于实现APP推送文本信息
		$fieldDB        = M('Field');
		$name = $fieldDB -> where(array('id' => $fieldid)) -> getField('name');
		return $name."：".$data."";
	}
	
	
	
	//处理批量提交的数据，重新组合数据
	private function DataParse($data){
		$ret = array();
		foreach($data as $k => $v){
			if(is_array($v)){
				foreach($v as $key => $val){
					$ret[$key][$k] = $val;
				}
			}
			
		}
		return $ret;
	}
	
	//批量保存数据
	public function saveformAll($fdata, $view = NULL) {
		$data = $this->DataParse($fdata);
			
		foreach($data as $v){
			if(isset($v['member_id'])){
				$v['is_add']=1;     //如果要添加审批则一定要is_add
				$this->saveform($v, $view);
			}
		}
	}
	
	//保存单个表单
	public function saveform($fdata, $view = NULL) {
		$formDB           = D('Form');
		$taskDB           = D('Task');
		$fieldDB          = M('Field');
		$memberDB         = D('Member');
		$missionDB        = D('Mission');
		$scheduleDB       = D('Schedule');
		$integral_ruleDB  = D('Integral_rule');
		$this->memberInfo = session('memberInfo');
		//验证表单的正确性
		if(isset($fdata['form_id']) && intval($fdata['form_id']) > 0){
			$formS = $formDB -> where(array('id' => intval($fdata['form_id']))) -> find();
		}else{
			$this->error = '表单错误！';
			return false;
		}
	
		//如果标题为空
		if(!isset($fdata['title']) || (isset($fdata['title']) && $fdata['title'] == '')){
			$fdata['title'] = $formS['name'].'';
		}
		
		foreach($fdata as $k => $v){
			$fieldtype = $fieldDB -> where(array('f_name' => $k, 'site_id' => __SITEID__)) -> getField('f_type');
			if($fieldtype == 8){
				$fdata[$k] = intval(strtotime($v));
			}
		}

        //获取页面提交的所有表单元素的数据集
        $data['object'] = serialize($fdata);
        //流水号
        $data['record'] = build_order_no();
        //任务类型 外部任务
        $data['missionType'] = 1;
        //任务状态 审核中
        $data['state'] = $fdata['status'];
        //标题
        $data['title'] = $fdata['title'];
        //问题详情
        $data['detail'] = isset($fdata['remark'])?$fdata['remark']:$fdata['detail'];
		//如果有规则的话，
		if(isset($fdata['integral'])){
			//存储规则类型ID
			$ruleId=array_shift(array_shift($fdata['integral']));
			$data['rule_topid']=$integral_ruleDB->where(['id'=>$ruleId['id']])->getField('type_id');
			$data['rule_topid']=$this->getpid($data['rule_topid']);
			

			//将规则名字和分数排列好，存入详情中
			$inteDetail=$integral_ruleDB->getIntegralName($fdata['integral']);
			$data['detail']=implode(' ',$inteDetail).$fdata['detail'];
		}
		//结束时间
		$data['starttime']=strtotime(intval($fdata['starttime']));
		$data['endtime']=strtotime(intval($fdata['endtime']));
        //当前表单ID
        $data['form_id'] = $fdata['form_id'];
		//是否临时任务（0非1是）
		$data['temptask']=$fdata['temptask']?$fdata['temptask']:0;

		$data['formcategory_id'] = $formS['formcategory_id'];
		
		$data['particular'] = $formS['particular'];
        //创建任务的时间
        $data['createtime'] = $fdata['createtime']?strtotime($fdata['createtime']):time();
		//表格分类
		$data['formula']=$fdata['formula'];
		$data['approver'] = $fdata['approver'];
		$data['approver'] = trim($fdata['approver'],',')==''?'':$fdata['approver'];
		$data['approvername'] = $fdata['approvername'];
		
        //当前站点ID
        $data['site_id'] = __SITEID__; 
		
		//任务ID
		if($fdata['task_id'] > 0){
		    $data['task_id'] = (int)$fdata['task_id'];
		}

		
		//如果有传值就为传值 ，否则为当前 用户ID
		$data['member_id'] = empty($this->memberInfo['id'])?0:intval($this->memberInfo['id']);
		$data['member_id']= empty($fdata['member_id'])?$data['member_id']:$fdata['member_id'];
		$data['membername']= empty($fdata['membername'])?'未领取':$fdata['membername'];
		$data['approver_id']=empty($fdata['approver'])?$this->memberInfo['id']:$fdata['approver'];
		$data['approvername']=empty($fdata['approvername'])?$this->memberInfo['name']:$fdata['approvername'];
		
		//如果有传值就为传值 ，否则为当前 用户名
		$data['proposername'] = $memberDB->where('id='.$data['member_id'])->getField('name');
		
		if($fdata['temp']){
			$data['temptask']=1;
		}
		
		$data['formtemplate'] = $formDB -> where(array('id' => $data['form_id'])) -> createTaskForm($view, $fdata, 0);
		
		
		if($data['temptask']!=0){
			$data['member_id']='0'; 
			$data['proposername']='';
		}
		//如果是添加那么将当前用户ID传值给创建人ID
		if($_POST['is_add'] == 1){
			$data['user_id']=intval($this->memberInfo['id']);
		}
		$data[C('TOKEN_NAME')] = $_SESSION[C('TOKEN_NAME')];
		//如果是在任务添加工作的话，将任务的负责人，创建人，或者是父工作的负责人也转为审核人
		if(intval($fdata['task_id']) > 0){
			$task=$taskDB->where('id='.$fdata['task_id'])->find();
			$data['reviewer_id']=$task['member_id'];
			$data['approver_id'] = 0;
			$data['approver'] = '';
			$data['approvername']=$task['member_name'];
			
			//如果创建者不是负责人pid > 0
			if(intval($fdata['pid']) > 0){
				$pm = $missionDB -> where(array('id' => intval($fdata['pid']))) -> find();
				if($pm){
					$data['reviewer_id']=$pm['member_id'];
			        $data['approver_id'] = 0;
			        $data['approver'] = '';
			        $data['approvername']=$pm['proposername'];
				}
			}
			
		}
		//个人信息登记指定积分管理员审批
		if($formS['particular'] == 2){
			$approver = getManagerList();
			//$approver[] = 0;
			if(!empty($approver)){
				$data['approver'] = ','.implode(',', $approver).',';
			    $data['approvername'] = array();
				$approvername = $memberDB->where('id in ('.implode(',',$approver).')')->Field('name') -> select();
				foreach($approvername as $k => $v){
					$data['approvername'][] = $v['name'];
				}
				$fdata['state'] = 0;
				$fdata['is_add'] = 1;
				$data['approvername'] = implode(',', $data['approvername']);
			}
		}
		
		Vendor('Pinyin.pinyin');
		$py=new cn2pinyin();
		$data['memberstring']=$py->get($data['proposername']);
        //创建任务数据对象
		//dump($fdata);
		$data['formtemplateText'] = $this->getFormText($data['form_id'], $fdata);
		
		$formtemplateText = array();
		
		if(isset($_POST['integral'])){
			//提交了积分规则
			$where['_logic'] = 'or';
			//dump($_POST['integral']);
			foreach($_POST['integral'] as $v){
				if(isset($v[0]['id'])){
					foreach($v as $key => $value){
						$where['id']  = $value['id'];
						$where['rid']  = $value['id'];
						$formtemplateText[] = $integral_ruleDB -> where(array('_complex' => $where, 'site_id' => __SITEID__)) -> getField('remark');
					}
				}
			}
		}
		$formtemplateText[] = $data['formtemplateText'];
		$data['formtemplateText'] = implode("\n", $formtemplateText);
		
        $cdata = $missionDB->create($data);
		if(!$cdata){
			$this->error = $missionDB -> getError();
			return false;
		}
		
		
		//判断is_add添加或修改
		$integral = $_POST['integral'];
		if($fdata['is_add']==1){
			$mid = $missionDB -> add();
			if($mid > 0){
				
				//更新任务的总分数
			    $integralret = $missionDB -> where(array('id' => $mid)) -> geteventIntegral($view,$integral);
				
				
				$missionDB -> where(array('id' => $mid))->setField('integralret',serialize($integralret));
				$taskDB -> where(array('id' => $data['task_id'], 'site_id' => __SITEID__)) -> SetEventIntegral();
			}
		}else{
			$taskid = $missionDB -> where(array('id' => $_POST['id'])) -> getField('task_id');
			$integralret = $missionDB -> where(array('id' => $_POST['id'])) -> geteventIntegral($view,$integral);

			$taskDB -> where(array('id' => $taskid, 'site_id' => __SITEID__)) -> SetEventIntegral();
			$mid = $missionDB -> where(array('id' => $_POST['id'])) ->save($data);
			//重新写入积分总数
			$integralret = $missionDB -> where(array('id' => $_POST['id'])) -> geteventIntegral($view,$integral);
			$missionDB -> where(array('id' => $_POST['id']))->setField('integralret',serialize($integralret));
			$taskDB -> where(array('id' => $taskid, 'site_id' => __SITEID__)) -> SetEventIntegral();
		}
        if ($mid !== false) {
			/*$integral = $_POST['integral'];
			$integralret = $missionDB -> where(array('id' => $mid)) -> geteventIntegral($view, $integral);
			
			// $integralret='' 
			$missionDB -> where(array('id' => $mid))->setField('integralret',serialize($integralret));
			$taskDB -> where(array('id' => $data['task_id'], 'site_id' => __SITEID__)) -> SetEventIntegral($integralret);*/
			
			if($data['task_id'] > 0){
				$taskDB -> where(array('id' => $data['task_id'], 'site_id' => __SITEID__)) -> updateprogress();
			}

			//如果是积分事件上面加分则直接审批(并添加审批记录)，直接通过，直接加分！
			if($fdata['access']=='Integral_log'){
				//直接更新是错误的，
				//$missionDB-> where(array('id' => $mid)) ->setField('state','3');
				$passdata['status'] = 1;
				$passdata['mission_id'] = $mid;
				$passdata['datatime']=$data['createtime'];
				$mission = $missionDB -> where(array('id' => $mid, 'site_id' => __SITEID__)) -> find();
				$intedataarr = unserialize($mission['integralret']);
				foreach($intedataarr as $k => $v){
					$passdata['integralmember_id'][] = $k;
					foreach($v['integral'] as $key => $val){
						$passdata['integralnum'][] = $val;
						$passdata['integraltype'][] = $key;
					}
				}
				if(isset($_POST['send'])){
					$passdata['send'] = 1;
				}
				if(isset($_POST['ticket'])){
					$passdata['ticket'] = 1;
				}
				$ret = $missionDB -> pass($passdata, $view);
				
				if($ret === false){
					$this->error = $missionDB -> getError();
					return false;
				}
			}
        }
    }
	//组合生成字段元素
	private function fieldDisposebootstrap($field, $data = ''){
		//表单id属性值数据
		$fid = $field['f_id'];
		//表单name属性值数据
		$fname = $field['f_name'];
		$name = $field['name'];
		//表单验证正则表达式数据
		$verify = $field['verify'];
		//表单验证信息数据
		$verifyHint = $field['verify_hint'];
		
		if($verify != ''){
			$verifystr = 'datatype="'.$verify.'" nullmsg="'.$verifyHint.'" errormsg="'.$verifyHint.'"';
		}else{
			$verifystr = '';
		}
		//表单type属性值数据
		if($field['f_type']==1){//文本框
			$type = ($fname == 'Binte' || $fname == 'Binte' || $fname == 'Binte') ? 'number' : 'text';
			$inputs = '<input style="display:inline;width:100%;'.($type=='number'?'width:100px;' : '').'" class="decorate form-control" value="'.$data.'" placeholder="'.$name.'" id="'.$fid.'" name="'.$fname.'[]" type="'.$type.'" '.$verifystr.' />';
		}else if($field['f_type']==2){//文件域
			$type ='file';
			$inputs = '<input enctype="multipart/form-data" id="'.$fid.'" name="'.$fname.'[]" type="'.$type.'" '.$verifystr.' />';
		
		}else if($field['f_type']==3){//单选按钮
			$type ='radio';
			foreach(unserialize($field['valueList']) as $v){
				
				$checked = '';
				if($data == $v['val']){
					$checked = ' checked="checked"';
				}
				$inputs .= '<label class="radio" style="display:inline-block; margin-bottom:5px; margin-right:15px;"><input id="'.$v['val'].'" value="'.$v['val'].'" name="'.$fid.'[]"'.$checked.' type="'.$type.'" '.$verifystr.' /><span>'.$v['lebal'].'</span></label>';
			}
				return $inputs;
			
		}else if($field['f_type']==4){
			$type ='checkbox';
			$i = 0;
			foreach(unserialize($field['valueList']) as $v){
				$checked = '';
				if($data == $v['val']){
					$checked = ' checked="checked"';
				}
				$inputs .= '<label class="radio" style="display:inline-block; margin-bottom:5px; margin-right:15px;"><input id="'.$v['val'].'" value="'.$v['val'].'" name="'.$fid.'[]"'.$checked.' type="'.$type.'" '.$verifystr.' /><span>'.$v['lebal'].'</span></label>';
				$i ++ ;
			}
				return $inputs;
			}else if($field['f_type']==5){//文本域
				$inputs .= '<textarea class="form-control" id="'.$v['val'].'" name="'.$fname.'[]" type="'.$type.'" '.$verifystr.' rows="1" >'.$data.'</textarea>';
				return $inputs;
			}else if($field['f_type']==7){
				//验证码
				$inputs .= '<button type="submit">'.$name.'</button>';
		    }elseif($field['f_type']==8){
				$inputs = '<input style="max-width:100px;cursor:pointer; display:inline;" readonly value="'.($data == '' ? '' :$data).'" class="scrollerinput decorate form-control datetimeinput" placeholder="'.$name.'" id="WdatePicker'.$field['id'].'" name="'.$fname.'[]" type="'.$type.'" '.$verifystr.' onclick="WdatePicker();" />';
			}
		return $inputs; 
	}
	//递归获取根分类
	public function getpid($id){
		if($id){
			$pid = D('Integral_ruletype')->where('id ='.$id)->getfield('pid');
			if($pid){
				return $this->getpid($pid);
			}else{
				return $id;
			}
		}else{
			return $id;	
		}
	}
}